package com.example.post.controller;
import com.example.post.model.Blog;
import com.example.post.model.User;
import com.example.post.services.impl.BlogServiceImpl;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class PostController {
    @Autowired
    private BlogServiceImpl blogService;

    @PostMapping("/api/posts")
    public ResponseEntity<String> createPost(HttpSession session, @RequestBody Blog postRequest) {

        String title = postRequest.getTitle();
        String content = postRequest.getContent();
        User user = (User) session.getAttribute("user");
        blogService.createPost(title, content, user.getId());
        return ResponseEntity.status(HttpStatus.OK).body("博客文章创建成功");
    }

    @DeleteMapping("/api/posts/{id}")
    public ResponseEntity<String> deletePost(@PathVariable int id) {
        blogService.deletePost(id);
        return ResponseEntity.status(HttpStatus.OK).body("博客文章删除成功");
    }

    @GetMapping("/api/posts/{id}")
    public ResponseEntity<Blog> getPostById(@PathVariable int id) {
        Blog post = blogService.getPostById(id);
        if (post == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        return ResponseEntity.status(HttpStatus.OK).body(post);
    }

    @GetMapping("/api/posts")
    public ResponseEntity<List<Blog>> getPostsByTitle(@RequestParam String title) {
        List<Blog> posts = blogService.getPostsByTitle(title);
        if (posts.isEmpty()) {

            return null;
        }
        return ResponseEntity.status(HttpStatus.OK).body(posts);
    }
    @PutMapping("/api/posts/{id}")
    public ResponseEntity<String> updatePostContent(@PathVariable int id, @RequestBody Blog postRequest) {
        Blog post = blogService.getPostById(id);
        if (post == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        String content = postRequest.getContent();
        blogService.updateContentById(id, content);
        return ResponseEntity.status(HttpStatus.OK).body("博客文章内容更新成功");
    }
}